﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Resources;
using System.Reflection;
using UIT.WPF.Renderers;
using System.Windows.Navigation;
#if !SILVERLIGHT
using System.IO.Packaging;
#endif

namespace UIT.WPF
{
    public class Application : System.Windows.Application
    {
        internal UIT.Application application;

        protected override void OnNavigating(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            Uri target = UIT.Context.Current.ResolveUrl(e.Uri);


            if (System.IO.Packaging.PackUriHelper.ComparePackUri(target, StartupUri) == 0)
            {
                e.Cancel = true;
                if (!MainWindow.IsVisible)
                    MainWindow.Show();
                return;
            }
            base.OnNavigating(e);
        }

        public Type ApplicationType { get; set; }

        protected override void OnStartup(System.Windows.StartupEventArgs e)
        {
            base.OnStartup(e);
            Context context = new Context();
            UIT.Context.GetContext = () => context;

            if (ApplicationType == null)
                ApplicationType = Assembly.GetEntryAssembly().GetExportedTypes().FirstOrDefault(t => t.BaseType == typeof(UIT.Application));

            if (ApplicationType == null)
                ApplicationType = typeof(UIT.Application);

            application = (UIT.Application)Activator.CreateInstance(ApplicationType);
            application.OnStart();

            var uri = StartupUri;
            WpfRendererManager.EnsureInitialized();
            MainWindow = (Window)WPF.Renderers.WpfRendererManager.Render(uri);
        }

        protected override void OnExit(ExitEventArgs e)
        {
            base.OnExit(e);
            if (application != null)
                application.OnStop();
        }
    }

}
